package com.chinasoft.dao;

import com.chinasoft.bean.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class StudentTest {
    InputStream is = null;
    SqlSessionFactory sqlSessionFactory = null;

    SqlSession sqlSession = null ;
    @Before
    public void beforemethod() throws IOException {
        //1.加载配置文件
        is = Resources.getResourceAsStream("MyTabisConfig.xml");
        //2.获取SqlSessionFactory
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通过SqlSessionFactory 获取sqlSession   参数为true-自动提交
        sqlSession = sqlSessionFactory.openSession(true);
    }
    @After
    public  void  end() throws IOException {
        //6.释放资源
        sqlSession.close();
        is.close();
    }
    @Test
    public void delete(){

        sqlSession.delete("StudentMapper.delete",6);
        //sqlSession.commit();

    }
    @Test
    public void update(){
        Student student = new Student(5,"李蕾",23);
        sqlSession.update("StudentMapper.update",student);


    }

    @Test
    public void insert(){
        Student student = new Student(5,"李蕾",20);
        sqlSession.insert("StudentMapper.insert",student);
        //sqlSession.commit();

    }


    @Test
    public void selectById(){
        Student stu = sqlSession.selectOne("StudentMapper.selectById",3);
        System.out.println("stu = " + stu);

    }


    @Test
    public void selectAll() throws IOException {  //返回值必须为空，没有参数，是public的;
        //1 加载配置文件
        //InputStream is = Resources.getResourceAsStream("MyTabisConfig.xml");
        //InputStream is = StudentTest.class.getClassLoader().getResourceAsStream("MyBatisConfig.xml");
//        System.out.println("is = " + is);

        //2 获取 SqlSessionFactory
        //SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通过SqlSessionFactory 获取SqlSession
        //SqlSession sqlSession = sqlSessionFactory.openSession();
        //4 执行映射文件中的sql语句
        List<Object> list = sqlSession.selectList("StudentMapper.selectAll");
        //5.处理结果
        list.forEach(System.out :: println);
        //6. 释放资源
//        sqlSession.close();
//        is.close();

    }
}
